#!/usr/bin/env bash

MAC_VERSION=`/usr/bin/sw_vers -productVersion | /usr/bin/awk -F. '{printf "%d%03d%03d\n", $1, $2, $3}'`

music_cmd="iTunes"
# check if >= Catalina (10.15)
# iTunes was renamed to Music
if [ `echo "${MAC_VERSION} > 10015000" | bc -l` ]
then
  music_cmd="Music"
fi

help () {
    cat<<__EOF__
Usage: m ${music_cmd} [OPTION] [ARGUMENTS]

Description: Control ${music_cmd} via command line

Options:
  --help            Show this help message
  --status          Show current status
  --play            Play current track
  --stop            Stop current track
  --pause           Pause current track
  --next            Play next track
  --prev            Play previous track
  --mute            Mute ${music_cmd}
  --vol LEVEL       Set volume to LEVEL (0-100)
  --quit            Quit ${music_cmd}
__EOF__
}

show_status(){
    state=`osascript -e "tell application \"${music_cmd}\" to player state as string"`
    echo "${music_cmd} is currently $state."
    if [ $state = "playing" ]; then
        artist=`osascript -e "tell application \"${music_cmd}\" to artist of current track as string"`
        track=`osascript -e "tell application \"${music_cmd}\" to name of current track as string"`
        echo "Current track $artist:  $track"
    fi
}

set_volume(){
    local value="${1}"
    local vol=`osascript -e "tell application \"${music_cmd}\" to sound volume as integer"`

    case "${value}" in
        [0-9]*)
            newvol="${1}"
            ;;
        *)
            help  && exit 1
            ;;
    esac
    osascript -e "tell application \"${music_cmd}\" to set sound volume to ${newvol}"
}

case $1 in
    --help)
        help
        ;;
    --status)
        show_status
        ;;
    --play)
        osascript -e "tell application \"${music_cmd}\" to play"
        ;;
    --pause)
        osascript -e "tell application \"${music_cmd}\" to pause"
        ;;
    --next)
        osascript -e "tell application \"${music_cmd}\" to next track"
        ;;
    --prev)
        osascript -e "tell application \"${music_cmd}\" to previous track"
        ;;
    --mute)
        osascript -e "tell application \"${music_cmd}\" to set mute to true"
        ;;
    --unmute)
        osascript -e "tell application \"${music_cmd}\" to set mute to false"
        ;;
    --vol)
        shift
        set_volume "$@"
        ;;
    --stop)
        osascript -e "tell application \"${music_cmd}\" to stop"
        ;;
    --quit)
        osascript -e "tell application \"${music_cmd}\" to quit"
        ;;
    *)
        help
        ;;
esac
